package com.heima.page.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.page.service.GeneratePageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.javassist.bytecode.ByteArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GeneratePageServiceImpl implements GeneratePageService {
    @Autowired
    Configuration configuration;
    @Autowired
    ArticleFeign articleFeign;

    @Resource(name = "minIOFileStorageService")
    FileStorageService fileStorageService;

    /**
     * 根据文章id生成静态页面
     *
     * @param articleId
     */
    @Override
    public void generateArticlePage(Long articleId) throws Exception {
        //获取数据
        ApArticleContent articleContent = articleFeign.findArticleContentById(articleId);
        if (articleContent == null || StringUtils.isBlank(articleContent.getContent())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApArticle article = articleFeign.findArticleById(articleId);
        //获取模板
        Template template = configuration.getTemplate("article.ftl");

        //封装数据
        List<Map> contentList = JSON.parseArray(articleContent.getContent(), Map.class);
        Map<String, Object> map = new HashMap();
        map.put("article", article);
        map.put("content", contentList);

        //*********
        ApAuthor author = articleFeign.findApAuthorById(article.getAuthorId());
        if (author==null){
            CustException.cust("文章作者为空 getAuthorId: "+article.getAuthorId());
        }
        Integer authorUserId = author.getUserId();
        map.put("authorApUserId",authorUserId);

        //生成静态页面
        StringWriter out = new StringWriter();
        template.process(map, out);
        InputStream is = new ByteArrayInputStream(out.toString().getBytes());
        //把生成的html文件上传到minio中
        String fileUrl = fileStorageService.store("article", articleId + ".html", "text/html", is);
        if (StringUtils.isBlank(fileUrl)){
            CustException.cust("上传到minio失败,articleId "+articleId);
        }
        //关闭io流
        is.close();
        out.close();
        //更新Article数据,添加static_url
        article.setStaticUrl(fileUrl);
        articleFeign.updateArticleById(article);


    }
}
